/**
 * Created by ZHOUSH on 12/22/2015.
 */
var path = {
    DSQL: 'b6464cd066492ef45e9cb3534abbef58_DATA',
    JXLS: '9d5cd1f6de6b65847f99984e1673b0ab_DATA',
    FODE: '71310a8e3da7a1fb413964340d77a207_DATA'
};
var TMPL_TYPE = ['DSQL', 'JXLS', 'FODE', 'ORCL'];
var Promise = require('promise');
var pread = Promise.denodeify(require('fs').readFile);
var pwrite = Promise.denodeify(require('fs').writeFile);
var si = require('search-index')({});
var psiadd = Promise.denodeify(si.add);
var psisearch = Promise.denodeify(si.search);
var init_module = function (app) {

};
var read = function () {
    return Promise.all(TMPL_TYPE.reduce(function (pre, cur) {
        if (cur in path) {
            pre.push(pread(__dirname + '/data/' + path[cur], 'utf-8').then(function (json) {
                return {
                    type: cur,
                    data: JSON.parse(json)
                }
            }));
        }
        return pre;
    }, [])).then(function (jsons) {
        return jsons.reduce(function (pre, item) {
            if (item.type == 'DSQL') {
                pre = pre.concat(item.data.map(function (dsql) {
                    var sql = '';
                    for (var i = 1; i <= 9; i++) {
                        if (dsql['SQL_STR_' + i]) {
                            sql += dsql['SQL_STR_' + i];
                        }
                    }
                    return {
                        key: dsql['TMPL_KEY'],
                        type: item.type,
                        sql: sql
                    }
                }))
            } else if (item.type == 'JXLS') {
                pre = pre.concat(item.data.map(function (jxls) {
                    var ret = {
                        key: jxls['ORA_RPT_RDF_NAME'],
                        type: item.type,
                        sql: jxls['SQL_STR']
                    };
                    var meta = {};
                    for (var prop in jxls) {
                        if (jxls.hasOwnProperty(prop) && prop != 'SQL_STR' && prop != 'ORA_RPT_RDF_NAME') {
                            meta[prop] = jxls[prop];
                        }
                    }
                    ret.meta = meta;
                    return ret;
                }))
            } else if (item.type == 'FODE') {
                pre = pre.concat(item.data.map(function (fode) {
                    var ret = {
                        key: fode['ORA_RPT_RDF_NAME'],
                        type: item.type,
                        sql: fode['SQL_STR']
                    };
                    var meta = {};
                    for (var prop in fode) {
                        if (fode.hasOwnProperty(prop) && prop != 'SQL_STR' && prop != 'ORA_RPT_RDF_NAME') {
                            meta[prop] = fode[prop];
                        }
                    }
                    ret.meta = meta;
                    return ret;
                }));
            }
            return pre;
        }, [])
    });
};
read().then(function (data) {
    return pwrite(__dirname + '/sql_summary.json', JSON.stringify(data));
}).then(console.log, console.log);
var cacheRead = function () {
    return pread(__dirname + '/sql_summary.json', 'utf-8').then(function (d0) {
        return pread(__dirname + '/orcl_summary.json', 'utf-8').then(function (d1) {
            return JSON.parse(d0).concat(JSON.parse(d1));
        })
    });
};
var word_search = function (query, cache) {
    var fun = cache ? cacheRead : read;
    return fun().then(function (data) {
        return psiadd(data, {}).then(function () {
            return psisearch({query: query})
        }).catch(function (err) {
            console.log(err);
        })
    })
};
var reg_search = function (query, cache) {
    var fun = cache ? cacheRead : read;
    return fun().then(function (data) {
        return data.reduce(function (pre, item) {
            for (var prop in query) {
                if (query.hasOwnProperty(prop) && item[prop]) {
                    query[prop].forEach(function (reg) {
                        if (typeof reg == 'string') {
                            reg = new RegExp(reg, 'ig');
                        }
                        var match, matches = [];
                        while ((match = reg.exec(item[prop])) != null) {
                            matches.push(match);
                        }
                        if (matches.length > 0) {
                            pre.push({
                                item: item,
                                matches: matches
                            });
                        }
                    });
                }
            }
            return pre;
        }, []);
    })
};
reg_search({
    key: [/\bRPT_EXPT_VENDOR_XLS_VW\b/ig]
}, true).then(function (data) {
    data.forEach(function (item) {
        var sql = item.item.sql;
        if (sql.join) sql = sql.join(';\r\n');
        console.log(sql);
        //if (item.item.type == 'ORCL') return;
        //pwrite(__dirname + '/temp_' + item.item.key + '.sql', sql);
        item.matches.forEach(function (match) {
            var input = match.input;
            var from = match.index - 40;
            from = from < 0 ? 0 : from;
            var to = match.index + 50;
            to = input.length < to ? input.length : to;
            var output = input.substring(from, to);
            console.log(item.item.key + '\t' + output.replace(/\s+/ig, ' '));
        })
    })
}, function (ex) {
    console.log(ex.stack);
});
//reg_search({
//    key: ['RPT_PIPELINE_JUSTFAB']
//}).then(console.log, function (ex) {
//    console.log(ex.stack);
//});
exports.read = read;
